<template>
  <div class="my-tree">
    <el-tree ref="treeRef" node-key="id" :data="treeData" :props="defaultProps" :expand-on-click-node="false"
      :show-checkbox="fromCreateTaskPage" @node-click="handleNodeClick" @check="handleCheck">
      <span class="custom-tree-node" slot-scope="{ node, data }">
        <el-tooltip class="item" effect="dark" :content="node.label" placement="bottom" :open-delay="500">
          <span class="custom-node-label">{{ node.label }}</span>
        </el-tooltip>
      </span>
    </el-tree>
  </div>
</template>

<script>
import  { mapState } from 'vuex'
export default {
  name: 'MyTree',
  data() {
    return {
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      parentTreeNodeList: [], //获取子节点,父节点数据组
    }
  },
  computed: {
    ...mapState({
        caseCategoryIds: state => state.case.caseCategoryIds,
    }),
  },
  props: {
    treeData: {
      type: Array,
      default: () => { [] }
    },
    fromCreateTaskPage: {
      type: Boolean,
      default: false
    },
    from: {
      type: String,
      default: ''
    }
  },
  mounted(){
    console.log('caseCategoryIds', this.caseCategoryIds)
    this.$refs.treeRef.setCheckedKeys(this.caseCategoryIds);
  },
  methods: {
    handleNodeClick(item, data) {
      // 若是metric页面调用MyTree组件，则将label处理后 发给 父组件
      if (this.from === 'metric') {
        this.parentTreeNodeList = []
        this.getParent(data)
        this.$emit('transferCheckedCategory', this.parentTreeNodeList)
      } else {
        // 若是worldsim \log2world页面调用MyTree组件，将点击的 当前的id,传递 给父组件
        this.$emit('TreeNodeClick', item.id)
      }

    },
    // check 勾选组
    handleCheck(data, checkinfo) {
      const checkedCaseCategoryIds = []
      if (checkinfo.checkedNodes && checkinfo.checkedNodes.length > 0) {
        checkinfo.checkedNodes.map(item => {
          checkedCaseCategoryIds.push(item.id)
        })
      }
      //  将左侧内置组勾选的 存入store
      this.$store.dispatch('case/setSelectedCaseCategoryIds', checkedCaseCategoryIds)
    },
    // 通过子节点获取父节点的数据
    getParent(node) {
      if (node.isLeaf === false && node.parent.parent === null) {
        this.parentTreeNodeList.push(node.data)
      } else {
        if (node.isLeaf === false && node.parent.parent !== null) {
          this.parentTreeNodeList.push(node.data)
          this.getParent(node.parent)
        } else if (node.isLeaf === true && node.parent.parent !== null) {
          this.parentTreeNodeList.push(node.data)
          this.getParent(node.parent)
        }
      }
    },
  }
}
</script>
<style lang="scss" scoped>
@import '@/styles/mixin.scss';

.my-tree {
  margin-top: 10px;
  overflow: auto;

  ::v-deep .el-tree-node__content {
    height: 40px;
    font-size: 14px;
    text-transform: uppercase;

    .custom-tree-node {
      @include text-ellipsis;
    }
  }
}
</style>